"""
    在开发环境下使用，
    制作生产成工具时需要把导入使用的第三方包，或者把使用的内容集成至该文件
"""
import sys
import os
curPath = os.path.abspath(os.path.dirname(__file__))
rootPath = os.path.split(curPath)[0]
sys.path.append(rootPath)

from utils.command import *
from utils.common import *

import requests
import json
from prettytable import PrettyTable


@command(name="add", value_type=str, help="todo task description,insert a task,example todo add 'my task 1'")
def add():
    task_description = OperationDict["add"].value
    try:
        result = insert_task(task_description)
    except requests.exceptions.ConnectionError:
        print("Connection refused")
        return False
    if result != "200":
        print(f'ErrorAdd:{error_code_to_text(result)}')
        return False
    print(f"todo task:{task_description} add ok!")
    return True


@command(name="done", value_type=str, help="complete a todo task")
def done():
    task_id = OperationDict["done"].value
    try:
        result = done_task(task_id)
    except requests.exceptions.ConnectionError:
        print("Connection refused")
        return False
    if result != "200":
        print(f'ErrorDone:{error_code_to_text(result)}')
        return False
    print(f"done task_id:{task_id} finish ok!")
    return True


@command(name="list", help="todo task description,insert a task,example todo add 'my task 1'")
@command(name="--state", value_type=str, help="[done/new]:view completed tasks or view the newly created task")
@command(name="--by", value_type=str, help="time[time ago]:view tasks before time,example --by 3 days ago")
@command(name="--created", value_type=str, help="time[time ago]:view tasks created by time ago")
def list():
    by_time = OperationDict['--by'].value
    create_time = OperationDict['--created'].value
    state = OperationDict['--state'].value
    try:
        if state is None:
            _result = select_tasks()
        else:
            _result = select_from_time_split(state, by_time, create_time)
    except requests.exceptions.ConnectionError:
        print("Connection refused")
        return False
    if _result["code"] != "200":
        print(f'ErrorList:{error_code_to_text(_result["code"])}')
    output_table(state, _result)
    return True


def done_task(task_id):
    res = requests.put(url + "/" + str(task_id))
    return get_json_code(res.text)


def insert_task(task_description):
    headers = {'content-type': "application/json"}
    json_data = json.dumps({'description': task_description})
    res = requests.post(url, data=json_data, headers=headers)
    return get_json_code(res.text)


def select_tasks():
    res = requests.get(url)
    return json_to_dict(res.text)


def select_from_time_split(state, by_time, create_time):
    create_time = str_to_time(create_time, HelpText)
    by_time = str_to_time(by_time, HelpText)
    if create_time is False or by_time is False:
        sys.exit(1)
    if create_time is not None:
        create_time = get_now_time()
    complete_time = None
    if state == "done":
        complete_time = by_time
    params = {"complete_time": complete_time,
              "create_time": create_time}
    res = requests.get(url + "/split", params)
    return json_to_dict(res.text)


# 制表输出
def output_table(state, todo_tasks):
    table = PrettyTable(["id", "name", "status", ""])
    state_to_call(state, todo_tasks, table)
    print(table)
    return True


def state_to_call(state, todo_tasks, table):
    _dict = {
        "done": call_done,
        "new": call_new
    }
    if _dict.get(state, None):
        func = _dict[state]
        return func(todo_tasks, table)
    return call_none(todo_tasks, table)


def check_data_dict(task_data_dict):
    if task_data_dict["sign"] != 0:
        new_status = "new"
    else:
        new_status = ""
    if task_data_dict["complete_time"] is not None:
        status = "done"
    else:
        status = "unfinished"
    return {"id": task_data_dict["todo_id"],
            "name": task_data_dict["name"],
            "status": status,
            "new_status": new_status}


def call_done(todo_tasks, table):
    for data_dict in todo_tasks["data"]["complete"]:
        _result = check_data_dict(data_dict)
        table.add_row([_result["id"], _result["name"], _result["status"], _result['new_status']])


def call_new(todo_tasks, table):
    for data_dict in todo_tasks["data"]["incomplete"]:
        _result = check_data_dict(data_dict)
        table.add_row([_result["id"], _result["name"], _result["status"], _result['new_status']])


def call_none(todo_tasks, table):
    for data_dict in todo_tasks["data"]:
        _result = check_data_dict(data_dict)
        table.add_row([_result["id"], _result["name"], _result["status"], _result['new_status']])


# code翻译
def error_code_to_text(error_code):
    print("You may need help:", sys.argv[0] + ' help')
    error_codes = {
        "200": "ok",
        "1001": "insert error",
        "1002": "done error",
        "1003": "update sign error",
        "1004": "select error",
        "1005": "method",
        "1006": "time error",
        "403": "拒绝访问",
        "404": "找不到资源",
        "405": "资源禁止"
    }
    if error_codes.get(error_code, None):
        return error_codes[error_code]
    return "Error: Can't understand the command-line statement"


if __name__ == '__main__':
    url = "http://127.0.0.1:8888/todo/api/tasks"
    run()